import { PcSeriveProvider } from "./../../../providers/pc-serive/pc-serive";
import { Component, ViewChild } from "@angular/core";
import {
  IonicPage,
  NavController,
  NavParams,
  ToastController,
  Navbar,
  AlertController,
} from "ionic-angular";
import { BaseUI } from "../../../common/baseUI";

/**
 * Generated class for the PcInputPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on 
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: "page-pc-input",
  templateUrl: "pc-input.html"
})
export class PcInputPage extends BaseUI {
  @ViewChild(Navbar) navBar: Navbar;
  saturation = []; //评测用户信息
  recordData = []; //排序数组
  numberMax; //规定最大分值
  maxNumbers = []; //最大数的有多少个
  score; //规则
  max; //最大值
  min; //最小值
  evalcode; //评测code
  evalname; //评测名称
  id; //评测小项的id
  state;//获取当前单项的状态
  constructor(public navCtrl: NavController, public navParams: NavParams, private toastCtrl: ToastController, private pcSerive: PcSeriveProvider, private alertCtrl: AlertController) {
    super();
    this.evalcode = this.navParams.get("evalcode"); //获取评测id
    this.id = this.navParams.get("id");//获取评测小项id
    this.state = this.navParams.get("state");//获取当前单项的状态

    this.pcSerive.getSmEvalList(this.evalcode).subscribe(data => {

      this.saturation = data["userList"]; //获取用户列表
      this.score = JSON.parse(data["evaluating"]["evaluatingproject"]); //获取规则
      this.numberMax = this.score[this.id]["value"]; //获取分值
      this.evalname = this.score[this.id]["name"]; //获取评测的名称

      //传入后台，查看是否有评价过，有的话去到数据显示出来，没有就显示默认数据
      let key = {
        name: this.evalname, //评测小项的名称
        type: this.id, //评测小项的id
        evaluatingCode: this.evalcode //评测id
      };

      this.pcSerive.getMyValue(key).subscribe(data => {
        //判断曾经有没有评测过，有的话替换分数，没有分数显示默认值

        if (data['status'] == 200) {
          //取出key和值，2个用来做查找和判断
          let i = data["data"];
          let listdata = [];

          for (const key in i) {
            if (i.hasOwnProperty(key)) {
              let n = {
                usercode: key,
                value: i[key]
              };
              listdata.push(n);
            }
          }
          //查找到每个人的id，将曾经评价过的分数替换每个人默认的分数
          for (let i = 0; i < listdata.length; i++) {
            for (let index = 0; index < this.saturation.length; index++) {
              if (this.saturation[index]['usercode'] == listdata[i]['usercode']) {
                this.saturation[index]["value"] = listdata[i]['value']
              }
            }
          }
          this.saturation.sort(this.comparecompare("value"));//排序算分差
        } else {
          //插入数组显示默认分值
          for (let i = 0; i < this.saturation.length; i++) {
            this.saturation[i]["value"] = Math.round(this.numberMax / 2);
          }
        }
      });
    });
  }

  //提交按钮
  openReport() {
    this.maxMin();
    this.bigNumber();
    //取出规则的值
    let rule: string = this.score[this.id]["score"];
    rule = JSON.parse(rule.replace(/'/g, '"'));

    if (this.max - this.min < rule["diff"]) {
      super.alertShow(this.alertCtrl, `高低分差小于${rule["diff"]}`);//高低差
    } else if (Math.max.apply(Math, this.maxNumbers.map(data => { return data.numBer; })) > this.saturation.length / 2) {
      super.alertShow(this.alertCtrl, `相同分数大于50%`);//阶梯分差
    } else {

      this.recordData = []; //排序出来的存放数据的数组
      //插入暂时存放排序的数组
      for (let i = 0; i < this.saturation.length; i++) {
        this.recordData.push(this.saturation[i]);
      }
      this.recordData.sort(this.comparecompare("value"));//排序算分差
      let number = Math.floor(this.recordData.length / 2);
      for (let i = 0; i < this.recordData.length - number; i++) {
        //做排序分差相减判断
        if (this.recordData[i]["value"] - this.recordData[i + number]["value"] < rule["sort"]) {
          super.alertShow(
            this.alertCtrl,
            `${this.recordData[i]["realname"]}${this.recordData[i]["value"]}减
            ${this.recordData[i + number]["realname"]}${this.recordData[i + number]["value"]}
            不能小于${rule["sort"]}`
          );
          return null;
        }
      }

      let lists = [];//要传给后台的数组
      let scores;//各项得分
      //收集每个人的评分，然后插入到lists的数组中
      for (let index = 0; index < this.recordData.length; index++) {
        let i = {
          name: this.score[this.id]["name"],
          value: this.saturation[index]["value"]
        };
        scores = i; //获取当前单项的评分
        let evals = {
          evaluatingcode: this.evalcode, //评测编号
          evaluatingallthescores: scores, //各项得分
          usercode: this.saturation[index]["usercode"] //被评测人id
        };
        lists.push(evals);
      }
      //传给后台的关键步骤，返回200插入成功，其他失败
      this.pcSerive.postEval(lists).subscribe(data => {
        if (data['status'] == 200) {
          // this.showToast(this.toastCtrl, "评价成功");
          this.navCtrl.pop();
        } else {
          this.showToast(this.toastCtrl, "评价失败，稍候再试");
        }
      });
    }
  }

  //更改界面左上角的返回触发的操作
  ionViewDidLoad() {
    this.navBar.backButtonClick = this.backButtonClick;
  }
  backButtonClick = (e: UIEvent) => {
    if (this.state == true) {
      this.navCtrl.pop();
    } else {
      super.showToast(this.toastCtrl, `评测项${this.evalname} 未填完`);
      this.navCtrl.pop();
    }
  }

  //跳转到帮助页面
  openHelp() {
    this.navCtrl.push("PcRequirementPage");
  }

  //计算最大数字有多少个，鬼知道有多少个呢
  bigNumber() {
    this.maxNumbers = [];
    for (let i = 0; i < this.saturation.length; i++) {
      let a = this.saturation[i]["value"]; //值
      let b = 0; //出现次数
      for (let n = 0; n < this.saturation.length; n++) {
        if (this.saturation[n]["value"] == a) {
          b++;
        }
      }
      this.maxNumbers.push({ value: a, numBer: b });
    }
  }

  //算最大最小值
  maxMin() {
    this.min = 0;
    this.max = 0;
    this.max = Math.max.apply(
      Math,
      this.saturation.map(data => {
        return data.value;
      })
    );
    this.min = Math.min.apply(
      Math,
      this.saturation.map(data => {
        return data.value;
      })
    );
  }

  //选择按照数组中的某个选项排序
  comparecompare(item) {
    return function (obj1, obj2) {
      let val1 = obj1[item];
      let val2 = obj2[item];
      if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
        val1 = Number(val1);
        val2 = Number(val2);
      }
      if (val1 < val2) {
        return 1;
      } else if (val1 > val2) {
        return -1;
      } else {
        return 0;
      }
    };
  }
}
